package com.sjtu.service.onstart;

import com.sjtu.service.JobAllocator;
import com.sjtu.service.cache.TaskInfoCache;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务的时间计算及执行
 * nerine
 * 1/25/2020
 */
@Component
public class JobScheduleManager implements InitializingBean {

    @Autowired
    private TaskInfoCache taskInfoCache;
    @Autowired
    private ThreadPoolTaskExecutor jobRollingThread;
    @Autowired
    private JobAllocator jobAllocator;

    @Override
    public void afterPropertiesSet() throws Exception {
        taskInfoCache.loadAllTaskIntoMemory();
        allocateTask();
    }

    void allocateTask() {
        ExecutorService es = Executors.newSingleThreadExecutor();
        es.submit(() -> {
            while(true) {
                taskInfoCache.getTaskCache().entrySet().forEach(entry -> {
                    jobRollingThread.execute(() -> {
                        jobAllocator.allocate(entry.getKey());
                    });
                });
                TimeUnit.MILLISECONDS.sleep(5000 - System.currentTimeMillis() % 1000);
            }
        });
    }
}
